package com.cqhz.quwan.ui.main.fragment

import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Looper
import android.support.v4.view.ViewPager
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.bigkoo.convenientbanner.ConvenientBanner
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator
import com.bigkoo.convenientbanner.holder.Holder
import com.blankj.utilcode.util.StringUtils
import com.cqhz.quwan.APP
import com.cqhz.quwan.ActivityInject
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.model.*
import com.cqhz.quwan.mvp.home.GuessContract
import com.cqhz.quwan.mvp.home.GuessPresenter
import com.cqhz.quwan.mvp.mine.AlipayContract
import com.cqhz.quwan.mvp.mine.AlipayPresenter
import com.cqhz.quwan.mvp.mine.MessageContract
import com.cqhz.quwan.mvp.mine.MessagePresenter
import com.cqhz.quwan.service.HomeService
import com.cqhz.quwan.ui.activity.BasketballLotteryActivity
import com.cqhz.quwan.ui.activity.ESportActivity
import com.cqhz.quwan.ui.activity.FootballLotteryActivity
import com.cqhz.quwan.ui.activity.MyPredictionActivity
import com.cqhz.quwan.ui.base.AbsFragment
import com.cqhz.quwan.ui.base.WebViewActivity
import com.cqhz.quwan.ui.buy.event.EventObj
import com.cqhz.quwan.ui.login.LoginActivity
import com.cqhz.quwan.ui.main.adapter.HotLotteryAdapter
import com.cqhz.quwan.ui.main.adapter.NewsAdapter
import com.cqhz.quwan.ui.main.order.OrderListActivity
import com.cqhz.quwan.ui.main.pager.CardItem
import com.cqhz.quwan.ui.main.pager.CardPagerAdapter
import com.cqhz.quwan.ui.main.pager.HotPagerAdapter
import com.cqhz.quwan.ui.main.pager.HotPagerItem
import com.cqhz.quwan.ui.widget.ProgressDialogFragment
import com.cqhz.quwan.ui.widget.ScrollableGridView
import com.cqhz.quwan.ui.widget.dialog.PrizeDialog
import com.cqhz.quwan.ui.widget.dialog.RewardDialog
import com.cqhz.quwan.ui.widget.guide.Guider
import com.cqhz.quwan.ui.widget.guide.model.GuidePage
import com.cqhz.quwan.ui.widget.guide.model.HighLight
import com.cqhz.quwan.util.*
import com.gongwen.marqueen.SimpleMF
import com.gongwen.marqueen.SimpleMarqueeView
import kotlinx.android.synthetic.main.fragment_guess.*
import me.militch.quickcore.core.HasDaggerInject
import me.militch.quickcore.mvp.model.ModelHelper
import me.militch.quickcore.util.ApiException
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import javax.inject.Inject

/**
 * 首页-竞猜页面
 * Created by Guojing on 2018/9/4.
 */
class GuessFragment : AbsFragment(), GuessContract.View, MessageContract.View, AlipayContract.View, HasDaggerInject<ActivityInject>, CardPagerAdapter.BindAlipayClickListener {

    @Inject
    lateinit var guessPresenter: GuessPresenter
    @Inject
    lateinit var messagePresenter: MessagePresenter
    @Inject
    lateinit var alipayPresenter: AlipayPresenter
    @Inject
    lateinit var modelHelper: ModelHelper
    private var loginBean: LoginBean? = null

    private var fistLoad = true
    private var hasNews = false

    // 初始化控件
    private lateinit var hotView: FrameLayout
    private lateinit var focusView: FrameLayout
    private lateinit var hotLottery: LinearLayout
    private lateinit var itemTitle: LinearLayout
    private lateinit var bannerLayout: LinearLayout
    private lateinit var cgjView: LinearLayout
    private lateinit var hotLotteryGridView: ScrollableGridView
    private lateinit var newsAdapter: NewsAdapter
    private lateinit var hotAdapter: HotLotteryAdapter// 热门游戏适配器
    private lateinit var ballTvs: Array<TextView>
    private lateinit var cbAd: ConvenientBanner<BannerItem>
    private var newsItems: List<HotNews> = ArrayList()
    private var hotItems: List<HotLottery> = ArrayList()
    private lateinit var blueBalls: IntArray
    private lateinit var redBalls: IntArray
    private lateinit var mv: SimpleMarqueeView<String>
    private lateinit var marqueeFactory: SimpleMF<String>
    private val md = ArrayList<String>()
    private lateinit var hotViewPager: ViewPager
    private lateinit var focusViewPager: ViewPager
    private lateinit var hotPagerAdapter: HotPagerAdapter
    private lateinit var viewPagerAdapter: CardPagerAdapter
    private lateinit var cgjImageView: ImageView
    private lateinit var progressDialog: ProgressDialogFragment
    private var ssqId: String? = null
    private var ssqPeriod: String? = null
    private var ssqInfo: HotLottery? = null
    private val mHandler = Handler(Looper.getMainLooper())
    private var dialog: Dialog? = null

    override fun initImmersionBar() {
        mImmersionBar!!.transparentStatusBar().init()
    }

    override fun inject(t: ActivityInject?) {
        t!!.inject(this)
    }

    companion object {
        fun newInstance() = GuessFragment()
    }

    override fun layout(): Int {
        return R.layout.fragment_guess
    }

    override fun showMsgData2(data: List<Msg2Entity>) {

    }

    override fun showMsgData(data: List<MsgItemBean>) {
        val bs = data.map { it.content ?: "" }
//        (refreshLayout.state.isFinishing).run4false {
//            refreshLayout.finishRefresh()
//        }
        // TODO 限制一条以上的数据滚动，单条数据不滚动。
        (bs.size > 1).run4true {
            if (fistLoad) {
                marqueeFactory.data = bs
            }
            mHandler.post {
                if (fistLoad) {
                    mv.startFlipping()
                    fistLoad = false
                }
            }
//            mv.startFlipping()
        }
    }

    override fun showHotNews(news: List<HotNews>) {
        if (news.isNotEmpty() && !hasNews) {
            lv_guess.addHeaderView(itemTitle)
            hasNews = true
        } else if (news.isEmpty() && hasNews) {
            lv_guess.removeHeaderView(itemTitle)
            hasNews = false
        }
        newsAdapter.setData(null)
        (refreshLayout.state.isFinishing).run4false {
            refreshLayout.finishRefresh()
        }
    }

    override fun showRequestError(e: ApiException) {
        super.showRequestError(e)
        (refreshLayout.state.isFinishing).run4false {
            refreshLayout.finishRefresh()
        }
    }

    override fun showHotLottery(hotLottery: List<HotLottery>) {
        hotAdapter.setData(hotLottery)
        APP.get()!!.currentLottery.clear()
        APP.get()!!.currentLottery.addAll(hotLottery)
        findSSQ(hotLottery)

    }

    private fun findSSQ(hotLottery: List<HotLottery>) {
        for (hot: HotLottery in hotLottery) {
            if (hot.id == "11") {
                ssqInfo = hot
            }
        }
    }

    override fun onStop() {
        super.onStop()
        mv.stopFlipping()
    }

    override fun initView() {
        EventBus.getDefault().register(this)
        if (APP.get()!!.loginInfo != null) {
            loginBean = APP.get()!!.loginInfo
        }
        messagePresenter.attachView(this)
        guessPresenter.attachView(this)
        alipayPresenter.attachView(this)

        hotView = inflate(R.layout.pager_hot_game)
        focusView = inflate(R.layout.pager_focus_game)
        hotLottery = inflate(R.layout.widget_hot_lottery)
        itemTitle = inflate(R.layout.widget_home_title)
        bannerLayout = inflate(R.layout.widget_banner)
        cgjView = inflate(R.layout.widget_cgj_layout)
        progressDialog = ProgressDialogFragment.new()
        with(view) {
            refreshLayout.setOnRefreshListener {
                guessPresenter.getBannerData(0)
                guessPresenter.getBannerData(1)

                guessPresenter.getHotLottery()
                guessPresenter.getNewsList()
                messagePresenter.getSysMsg()

                val state = PreferenceHelper.getInstance(context!!).getInt(KeyContract.STATE, KeyContract.STATE_HOT_MATCH)
                if (state == KeyContract.STATE_FOCUS_MATCH) {
                    queryFocusMatch()
                } else {
                    queryHotMatch()
                }
            }
        }
        with(bannerLayout) {
            cbAd = findViewById(R.id.cb_ad)
            mv = findViewById(R.id.simpleMarqueeView)
        }
        with(hotLottery) {
            hotLotteryGridView = findViewById(R.id.gv_hot_lottery)
        }
        with(hotView) {
            hotViewPager = findViewById(R.id.viewPager)
        }
        with(focusView) {
            focusViewPager = findViewById(R.id.viewPager)
        }
        with(cgjView) {
            cgjImageView = findViewById(R.id.iv_cgj)
        }

        lv_guess.addHeaderView(bannerLayout)
        val state = PreferenceHelper.getInstance(context!!).getInt(KeyContract.STATE, KeyContract.STATE_HOT_MATCH)
        if (state == KeyContract.STATE_FOCUS_MATCH) {
            lv_guess.addHeaderView(focusView)
        } else {
            lv_guess.addHeaderView(hotView)
        }
        lv_guess.addHeaderView(cgjView)
        lv_guess.addHeaderView(hotLottery)

        // 初始化数据适配器
        newsAdapter = NewsAdapter(context!!)
        newsAdapter.itemClickListener = { _, item ->
            guessPresenter.saveReaderNum(item.id)
        }
        lv_guess.adapter = newsAdapter

        hotAdapter = HotLotteryAdapter(context!!)
        hotLotteryGridView.adapter = hotAdapter
        hotLotteryGridView.setOnItemClickListener { _, _, position, _ ->
            val item = hotAdapter.getItem(position)
            val isEnabled = item.saleStatus ?: 0 == 1

            if (isEnabled) {
                hotLotteryGridView.isEnabled = false
                when (item.id) {
                    "10" -> {// 游戏电竞
                        var intent = Intent(activity, ESportActivity::class.java)
                        intent.putExtra(KeyContract.Title, "电竞")
                        intent.putExtra(KeyContract.LotteryId, item.id)
                        intent.putExtra(KeyContract.Position, "0")
                        startActivity(intent)
                        hotLotteryGridView.isEnabled = true
                    }
                    "21" -> {// 过关足球（混合投注）
                        val intent = Intent(context, FootballLotteryActivity::class.java)
                        intent.putExtra(KeyContract.LotteryId, item.id)
                        intent.putExtra(KeyContract.Position, 0)
                        startActivity(intent)
                        hotLotteryGridView.isEnabled = true
                    }
                    "22" -> {// 单关足球（单关固定）
                        val intent = Intent(context, FootballLotteryActivity::class.java)
                        intent.putExtra(KeyContract.LotteryId, item.id)
                        intent.putExtra(KeyContract.Position, 1)
                        startActivity(intent)
                        hotLotteryGridView.isEnabled = true
                    }
                    "23" -> {// 欢乐猜球
                        var intent = Intent(activity, ESportActivity::class.java)
                        intent.putExtra(KeyContract.Title, "猜球")
                        intent.putExtra(KeyContract.LotteryId, item.id)
                        intent.putExtra(KeyContract.Position, "0")
                        startActivity(intent)
                        hotLotteryGridView.isEnabled = true
                    }
                    "24" -> {// 竞猜篮球
//                        showToast("暂停销售")
                        val intent = Intent(context, BasketballLotteryActivity::class.java)
                        intent.putExtra(KeyContract.LotteryId, item.id)
                        intent.putExtra(KeyContract.Position, 0)
                        startActivity(intent)
                        hotLotteryGridView.isEnabled = true
                    }
                }
            } else {
                showToast("暂停销售")
                hotLotteryGridView.isEnabled = true
            }
        }

        marqueeFactory = SimpleMF(activity)
        marqueeFactory.data = listOf()
        mv.setMarqueeFactory(marqueeFactory)
//        guessPresenter.getBannerData(0)
//        guessPresenter.getBannerData(1)
//        guessPresenter.getHotLottery()
//        guessPresenter.getNewsList()
//        if (loginBean != null) {
//            guessPresenter.getWindowList(loginBean!!.userId!!)
//        }
//        messagePresenter.getSysMsg()
//        mv.startFlipping()

        guessPresenter.getBannerData(3)

        if (state == KeyContract.STATE_FOCUS_MATCH) {
            queryFocusMatch()
        } else {
            queryHotMatch()
        }
    }

    private fun showFocusGuide(target: View) {
//        Guider.with(this)
//                .setLabel("home_page_1")
//                .alwaysShow(true)
//                .addGuidePage(GuidePage.newInstance()
//                        .addHighLight(target, HighLight.Shape.RECTANGLE)
//                        .setEverywhereCancelable(false)
//                        .setLayoutRes(R.layout.guide_home_focus)
//                        .setOnLayoutInflatedListener { view, controller ->
//                            view.findViewById<ImageView>(R.id.iv_next).setOnClickListener({
//                                controller.remove()
//                                showHotGuide()
//                            })
//                        })
//                .show()
    }

    private fun showHotGuide() {
        val childAt = hotLotteryGridView.getChildAt(0)
        if (childAt != null) {
            val iconView = childAt.findViewById<ImageView>(R.id.lottery_icon)
            Guider.with(this)
                    .setLabel("home_page_2")
                    .alwaysShow(true)
                    .addGuidePage(GuidePage.newInstance()
                            .addHighLight(iconView, HighLight.Shape.CIRCLE)
                            .setEverywhereCancelable(false)
                            .setLayoutRes(R.layout.guide_home_jczq, R.id.iv_next)
                            .setOnLayoutInflatedListener { _, controller ->
                                PreferenceHelper.getInstance(context!!).putBoolean("guide_home_focus", false)
                                controller.remove()
                            })
                    .show()
        }
    }

    private fun queryHotMatch() {
        modelHelper.request(modelHelper.getService(HomeService::class.java).queryHotMatch(),
                {
                    if (it.size > 0) {
                        hotView.visibility = View.VISIBLE
                        hotPagerAdapter = HotPagerAdapter(context, modelHelper)
                        for (data: HotBean in it) {
                            hotPagerAdapter.addCardItem(context, HotPagerItem(data))
                        }

                        hotViewPager.adapter = hotPagerAdapter
                        hotViewPager.offscreenPageLimit = 2

                        val childAt = hotViewPager.getChildAt(0)
                        val isShow = PreferenceHelper.getInstance(context!!).getBoolean("guide_home_focus", true)
                        if (childAt != null && isShow) {
                            showFocusGuide(childAt)

                        }
                    } else {
                        hotView.visibility = View.GONE
                    }
                }, { hotView.visibility = View.GONE })
    }

    private fun queryFocusMatch() {
        modelHelper.request(modelHelper.getService(HomeService::class.java).queryFocusMatch(),
                {
                    if (it.size > 0) {
                        focusView.visibility = View.VISIBLE
                        viewPagerAdapter = CardPagerAdapter(context, modelHelper)
                        viewPagerAdapter.setBindAlipayClickListener(this)
                        for (data: FocusBean in it) {
                            viewPagerAdapter.addCardItem(context, CardItem(data))
                        }

                        focusViewPager.adapter = viewPagerAdapter
                        focusViewPager.offscreenPageLimit = 2

                        val childAt = focusViewPager.getChildAt(0)
                        val isShow = PreferenceHelper.getInstance(context!!).getBoolean("guide_home_focus", true)
                        if (childAt != null && isShow) {
                            showFocusGuide(childAt)

                        }
                    } else {
                        focusView.visibility = View.GONE
                    }
                },
                {
                    focusView.visibility = View.GONE
                })
    }

    override fun setWindowList(list: List<WindowBean>) {
        // type 类型 1-中奖；2-邀请首单；3-邀请首冲；4-每日首单；5-新用户注册
        for (i in list.size - 1 downTo 0) {
            when (list[i].type) {
                "1" -> {
                    PrizeDialog(context)
                            .builder()
                            .setMsg(list[i].title)
                            .setBean(list[i].content)
                            .setActionConfirm("查看中奖订单") { startActivity(Intent(activity, if (loginBean == null) LoginActivity::class.java else OrderListActivity::class.java)) }
                            .show()
                }
                "6" -> {
                    PrizeDialog(context)
                            .builder()
                            .setMsg(list[i].title)
                            .setBean(list[i].content)
                            .setActionConfirm("查看中奖订单") { startActivity(Intent(activity, if (loginBean == null) LoginActivity::class.java else MyPredictionActivity::class.java)) }
                            .show()
                }
                else -> {
                    RewardDialog(context)
                            .builder()
                            .setMsg(list[i].title)
                            .setBean(list[i].content)
                            .setActionConfirm("确定")
                            .show()
                }
            }
        }
    }

    /**
     * 点击绑定支付宝
     */
    override fun onBindAlipayClick() {
        AlertDialog.Builder(context)
                .setTitle("温馨提示").setMessage("为了账户安全，请绑定支付宝")
                .setNegativeButton("取消") { dialog, _ ->
                    dialog.dismiss()
                }.setPositiveButton("确定") { dialog, _ ->
                    alipayPresenter.auth4alipay()

                }.setCancelable(false)
                .create().show()
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!isHidden) {
            this.onResume()
        } else {
            this.onPause()
            if (refreshLayout.state.isFinishing) {
                refreshLayout.finishRefresh()
            }
        }
    }

    override fun onResume() {
        super.onResume()
        UmengAnalyticsHelper.onPageStart("竞猜")// 统计页面
        UmengAnalyticsHelper.onResume(context())
        if (APP.get()!!.loginInfo != null) {
            loginBean = APP.get()!!.loginInfo
        }

        guessPresenter.getBannerData(0)
        guessPresenter.getBannerData(1)
        guessPresenter.getHotLottery()
        guessPresenter.getNewsList()
        if (loginBean != null) {
            guessPresenter.getWindowList(loginBean!!.userId!!)
        }
        messagePresenter.getBroadcast()
    }

    /**
     * 加在广告
     * @param type   0：首页顶部 1：首页中部 2：个人中心 3：弹窗 4:资讯首页
     * @param banner 广告数据列表
     */
    override fun loadBanner(type: Int, banner: List<BannerItem>) {
        when (type) {
            0 -> {
                // 初始化 Banner 控件
                val params = cbAd.layoutParams as ViewGroup.LayoutParams
                params.height = activity!!.getScreenWidth() * 300 / 750
                cbAd.layoutParams = params
                if (banner.isEmpty()) {
                    params.height = 1
                    cbAd.layoutParams = params
                    return
                }

                cbAd.setPages(object : CBViewHolderCreator {
                    override fun createHolder(itemView: View): ImageHolderView {
                        return ImageHolderView(itemView, context!!)
                    }

                    override fun getLayoutId(): Int {
                        return R.layout.item_image_view
                    }
                }, banner).setOnItemClickListener { position ->
                    val bi = banner[position]
                    if (!StringUtils.isEmpty(bi.linkUrl)) {
                        val url = Tools.urlCV(bi.linkUrl)
                        val intent = Intent(context, WebViewActivity::class.java)
                        intent.putExtra(KeyContract.Url, url)
                        intent.putExtra(KeyContract.BannerId, bi.id)
                        intent.putExtra(KeyContract.Title, "活动")
                        intent.putExtra(KeyContract.EnableRefresh, false)
                        startActivity(intent)
                    }
                }

                if (!cbAd.isTurning && banner.size > 1) {
                    cbAd.setPageIndicator(intArrayOf(R.drawable.banner_btn_n, R.drawable.banner_btn_s))
                            .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                            .startTurning(5000)
                }
            }
            1 -> {
                if (!TextUtils.isEmpty(banner[0].linkUrl)) {
                    cgjImageView.visibility = View.VISIBLE
                    cgjImageView.setLoadImage(context!!, banner[0].imgUrl, R.mipmap.banner_cgj_bg)
                    cgjView.setOnClickListener {
                        val loginBean = APP.get()!!.loginInfo
                        if (loginBean == null) {
                            startActivity(Intent(context(), LoginActivity::class.java))
                            return@setOnClickListener
                        }
                        val intent = Intent(context, WebViewActivity::class.java)
                        intent.putExtra(KeyContract.Title, "邀请好友")
                        intent.putExtra(KeyContract.Url, "${banner[0].linkUrl}?user_id=${loginBean?.userId
                                ?: ""}&new=123")
                        intent.putExtra(KeyContract.EnableRefresh, false)
                        startActivity(intent)
                    }
                } else {
                    cgjImageView.visibility = View.GONE
                }
            }
            3 -> {
                if (banner.isNotEmpty()) {
                    dialog = Dialog(context, R.style.ImageDialogStyle)
                    dialog!!.setContentView(R.layout.layout_image_dialog)
                    val imageView = dialog!!.findViewById(R.id.iv_dialog) as ImageView
                    imageView.setLoadImage(context(), banner[0].imgUrl, R.drawable.mall_img_txty)
                    // 选择true的话点击其他地方可以使dialog消失，为false的话不会消失
                    dialog!!.setCanceledOnTouchOutside(true) // Sets whether this dialog is
                    val w = dialog!!.window
                    val lp = w.attributes
                    lp.x = 0
                    lp.y = 40
                    dialog!!.onWindowAttributesChanged(lp)
                    imageView.setOnClickListener { dialog!!.dismiss() }
                    dialog!!.show()
                }
            }
        }
    }

    /**
     * 图片轮转实现
     */
    internal class ImageHolderView(itemView: View, private val context: Context) : Holder<BannerItem>(itemView) {
        private var imageView: ImageView? = null

        override fun initView(itemView: View) {
            imageView = itemView.findViewById(R.id.imageView)
            imageView!!.scaleType = ImageView.ScaleType.FIT_XY
        }

        override fun updateUI(item: BannerItem) {
            imageView!!.setLoadImage(context, item.imgUrl, 0)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        guessPresenter.detachView()
        messagePresenter.detachView()
        alipayPresenter.detachView()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun showDialog(event: EventObj) {
        if (event.key == 0x9999) {
            if (event.value as Boolean? == true) {
//                progressDialog.setText("正在加载中...")
                progressDialog.show(childFragmentManager, "")
            } else if (progressDialog.isVisible) {
                progressDialog.dismiss()
            }
        }
    }

    override fun onDetach() {
        super.onDetach()
        EventBus.getDefault().unregister(this)
    }

    override fun onPause() {
        super.onPause()
        UmengAnalyticsHelper.onPageEnd("竞猜")// 统计页面
        UmengAnalyticsHelper.onPause(context())
    }

    override fun alipayAuthCallBack(authData: AlipayAuthData) {
        guessPresenter.bindAlipay(APP.get()!!.loginInfo!!.userId!!, authData)
    }
}
